package com.cyou.qb.front.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cyou.nad.utils.jmx.FrameWorkLogHelper;

/**
 * 用于记录action的执行效率日志，包括执行时间，失败是参数
 * 需要在jmx中设置IS_CONTROLLER_PROCESS_LOG_ENABLE 为true
 * @author luzhaoman
 *
 */
public class ControllerProcessLogInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {
	
	private Log log = LogFactory.getLog(getClass());
	
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ControllerProcessLogInterceptor");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		long beginTime = System.currentTimeMillis();//1、开始时间  
		startTimeThreadLocal.set(beginTime);//线程绑定变量（该数据只有当前请求的线程可见）  
		return true;//继续流程  
	}

	@SuppressWarnings("unchecked")
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		long endTime = System.currentTimeMillis();//2、结束时间  
		long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
		startTimeThreadLocal.remove();
		long consumeTime = endTime - beginTime;//3、消耗的时间  
		if(FrameWorkLogHelper.IS_CONTROLLER_PROCESS_LOG_ENABLE()){
			log.info(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));
		}
		if(ex!=null){
			if(FrameWorkLogHelper.IS_CONTROLLER_PROCESS_LOG_ENABLE()){
				StringBuilder sb = new StringBuilder();
				Enumeration<String> parameterNames = request.getParameterNames();
				while (parameterNames.hasMoreElements()) {
					String obj =parameterNames.nextElement();
					sb.append(obj).append("=").append(request.getParameter(obj)).append(",");
				}
				log.warn(String.format("%s process error ,param：%s", request.getRequestURI(),sb),ex);
			}
		}
	}

}
